package com.example.myys.data.repository

import com.alibaba.fastjson2.JSON
import com.example.myys.Constants
import com.example.myys.MyApplication
import com.example.myys.data.InventoryDatabase
import com.example.myys.data.entity.ChapterBean
import com.example.myys.data.entity.DataBean
import com.example.myys.network.HtmlClient
import com.example.myys.network.parse.YsDataSource
import com.example.myys.util.FileUtil

class BookRepository {
    val htmlClient = HtmlClient
    val bookDao=InventoryDatabase.getInstance(MyApplication.instance).dataBeanDao()
    val chapterDao=InventoryDatabase.getInstance(MyApplication.instance).chapterDao()
    val TYPE=Constants.XS
    val SOURCE_NAME="XsBqg"

    private val isChecked = SettingLinkRepository.getSettingByTypeIsChecked(TYPE)
    private val dataJson =
        if (isChecked != null) JSON.parseObject(isChecked.value) else JSON.parseArray(
            FileUtil.fileToJsonStr("xsjk.json")
        ).getJSONObject(0)

    //获取书城推荐
    suspend fun getBookRecommend():List<DataBean>?{
        val htmllist=htmlClient.getRecommend(SOURCE_NAME,"")
        var sctj=htmllist
        return sctj
    }
    //搜索书籍
    suspend fun getBookByKeyword(keyword:String):List<DataBean>?{
        YsDataSource.printValue()
        return htmlClient.getSearchByKeword(SOURCE_NAME,keyword)
    }
    //加入书架
    suspend fun addBookShelf(dataBean:DataBean){
        dataBean.type=TYPE
        val id=bookDao.insert(dataBean)
        val chapterList=htmlClient.getChapterList(SOURCE_NAME,dataBean.url,id.toInt())
        if (chapterList != null) {
            chapterDao.insertList(chapterList)
        }
    }
    //获取书架
    suspend fun getBookShelf():List<DataBean>{
        return bookDao.getListByType(TYPE)
    }

    //删除收藏
    suspend fun deleteShelf(dataBean: DataBean) {
        val chapters = chapterDao.getListByDataBeanId(dataBean.id)
        chapterDao.deleteList(chapters)
        bookDao.delete(dataBean)
    }
    //获取列表
    suspend fun getBookChapterList(dataUrl:String,dataId:Int):List<ChapterBean>{
        var chapterList=chapterDao.getListByDataBeanId(dataId)
        if(chapterList.isEmpty()){
            chapterList= htmlClient.getChapterList(SOURCE_NAME,dataUrl,dataId)!!
        }
        return chapterList
    }
    //获取内容
    suspend fun getBookContent(chapterUrl:String,id:Int,dataId: Int):String?{
        var chapter=chapterDao.getChapterContent(id,dataId)
        var content=""
        if(chapter!=null&&chapter.content.isNotEmpty()){
            content=chapter.content
        }else{
           val htmlcontent= htmlClient.getChapterContent(SOURCE_NAME,chapterUrl)
            if(htmlcontent!=null){
                content=htmlcontent
                if(chapter!=null){
                    chapter.content=htmlcontent
                    chapterDao.update(chapter)
                }
            }
        }
        return content
    }
}